﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;
using System.IO;

namespace C
{
    public class ProductImageController
    {
        public static void Insert(ProductImage a)
        {
            HCDataContext db = new HCDataContext();
            db.ProductImages.InsertOnSubmit(a);
            db.SubmitChanges();
        }

        public static void Update(ProductImage a, HCDataContext db)
        {
            db.SubmitChanges();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            ProductImage a = db.ProductImages.Where(
                ik => ik.ProductImageId == id).First();

            // Xoa file vat ly
            if (a.URL.StartsWith("/"))
            {
                string filePath = HttpContext.Current.Server.MapPath("~" + a.URL);
                if (File.Exists(filePath)) File.Delete(filePath);
            }

            // Xoa record trong database
            db.ProductImages.DeleteOnSubmit(a);
            db.SubmitChanges();
        }

        public static ProductImage GetByID(int id, HCDataContext db)
        {
            return db.ProductImages.Where(
                ik => ik.ProductImageId == id).FirstOrDefault();
        }

        public static ProductImage GetByID(int id)
        {
            return GetByID(id, new HCDataContext());
        }

        public static ProductImage GetMainImage(Product product)
        {
            List<ProductImage> listProductImage = product.ProductImages.ToList();
            if (listProductImage.Where(ik => ik.IsMainImage).Count() > 0)
                return listProductImage.Where(ik => ik.IsMainImage).First();
            else
                return listProductImage.FirstOrDefault();
        }

        public static string GetMainImageURL(Product product)
        {
            ProductImage pi = GetMainImage(product);
            if (pi != null) return pi.URL;
            else return "/Image/no_photo.jpeg";
        }
    }
}